#!/usr/bin/python

# Get references

from pyodm.document import Document
from pyodm.fields import *
from pyodm.criteria import Criteria

class Referree2Document(Document):
    field1 = StringField()
    field2 = StringField()

class Referrer2Document(Document):
    field1 = StringField()
    field2 = IntegerField()
    ref = ReferenceField(Referree2Document)

obj1 = Referrer2Document(field1="complex11", field2="complex12")
obj1.save()
ref11 = Referree2Document(field1="reffield11", field2="reffield21")
ref12 = Referree2Document(field1="reffield12", field2="reffield22")
ref13 = Referree2Document(field1="reffield13", field2="reffield23")
ref14 = Referree2Document(field1="reffield14", field2="reffield24")
obj1.ref.add(ref11); obj1.ref.add(ref12);
obj1.ref.add(ref13); obj1.ref.add(ref14)
ref11.save(); ref12.save(); ref13.save(); ref14.save()

obj2 = Referrer2Document(field1="complex21", field2="complex22")
obj2.save()
ref21 = Referree2Document(field1="reffield11", field2="reffield21")
ref22 = Referree2Document(field1="reffield12", field2="reffield22")
ref23 = Referree2Document(field1="reffield13", field2="reffield23")
ref24 = Referree2Document(field1="reffield14", field2="reffield24")
obj2.ref.add(ref21); obj2.ref.add(ref22);
obj2.ref.add(ref23); obj2.ref.add(ref24)
ref21.save(); ref22.save(); ref23.save(); ref24.save()

refobjs = Referree2Document.get()
print "Total number of referrees: %s" % len(refobjs)

crit1 = Criteria("field1", ">=", "reffield12")
crit2 = Criteria("field2", "<=", "reffield23")
objs = Referrer2Document.get()
refobjs = objs[1].ref.get([crit1, crit2])

for ref in refobjs:
    print "Key: %s\nfield1: %s\nfield2: %s\n=================\n" % (ref.getKey(), ref.field1, ref.field2)

print "ref12 == refobjs[0]: %s" % (ref12 == refobjs[0])
print "ref13 == refobjs[1]: %s" % (ref13 == refobjs[1])
print "ref22 == refobjs[0]: %s" % (ref22 == refobjs[0])
print "ref23 == refobjs[1]: %s" % (ref23 == refobjs[1])

